<template>
  <div class="inventory-management">
    <div class="page-header">
      <h2>库存管理</h2>
      <div class="header-actions">
        <el-button type="warning" @click="fetchLowStockItems" :loading="lowStockLoading">
          <el-icon><Warning /></el-icon>
          库存预警
        </el-button>
        <el-button type="primary" @click="refreshData">
          <el-icon><Refresh /></el-icon>
          刷新
        </el-button>
      </div>
    </div>

    <!-- 库存预警提示 -->
    <el-alert
      v-if="lowStockItems.length > 0"
      :title="`发现 ${lowStockItems.length} 项库存不足，请及时补货！`"
      type="warning"
      :closable="false"
      show-icon
      class="low-stock-alert">
      <template #default>
        <div class="low-stock-details">
          <span v-for="(item, index) in lowStockItems.slice(0, 3)" :key="item.factoryNo">
            {{ item.factoryNo }}({{ item.productName }}: {{ item.currentStockQuantity }}PCS)
            <span v-if="index < Math.min(lowStockItems.length, 3) - 1">、</span>
          </span>
          <span v-if="lowStockItems.length > 3">等...</span>
        </div>
      </template>
    </el-alert>

    <!-- 搜索条件区域 -->
    <el-card class="search-card">
      <template #header>
        <span>搜索条件</span>
        <el-button type="text" @click="resetSearch" style="float: right;">重置</el-button>
      </template>
      
      <el-form :model="searchForm" inline class="search-form">
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="客户代码">
              <el-select v-model="searchForm.customerCode" filterable
                         placeholder="选择客户代码" clearable style="width: 100%;">
                <el-option v-for="customer in customers" :key="customer.customerCode"
                          :label="customer.customerCode" :value="customer.customerCode"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="客户名称">
              <el-input v-model="searchForm.customerName" placeholder="客户名称" clearable/>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="产品名称">
              <el-input v-model="searchForm.productName" placeholder="产品名称" clearable/>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="物料编码">
              <el-input v-model="searchForm.materialCode" placeholder="物料编码" clearable/>
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="厂内编号">
              <el-input v-model="searchForm.factoryNo" placeholder="厂内编号" clearable/>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="业务员">
                            <el-select v-model="searchForm.salesperson" filterable allow-create default-first-option
                         placeholder="选择或输入业务员" clearable style="width: 100%;">
                <el-option v-for="emp in employees" :key="emp.employeeCode"
                           :label="emp.employeeName" :value="emp.employeeName"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="库存状态">
              <el-select v-model="searchForm.status" placeholder="选择库存状态" clearable style="width: 100%;">
                <el-option label="有库存" value="有库存"/>
                <el-option label="无库存" value="无库存"/>
                <el-option label="预警" value="预警"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="最小库存">
              <el-input-number 
                v-model="searchForm.minStock" 
                :min="0" 
                placeholder="最小库存预警"
                controls-position="right"
                style="width: 100%;">
              </el-input-number>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="24" style="text-align: center;">
            <el-button type="primary" @click="handleSearch" :loading="loading">
              <el-icon><Search /></el-icon>
              搜索
            </el-button>
            <el-button @click="resetSearch">
              <el-icon><RefreshLeft /></el-icon>
              重置
            </el-button>
          </el-col>
        </el-row>
      </el-form>
    </el-card>

    <!-- 库存列表 -->
    <el-card class="table-card">
      <template #header>
        <span>库存列表</span>
        <div style="float: right;">
          <el-tag type="success" size="small">
            共 {{ pagination.total }} 项库存
          </el-tag>
          <el-divider direction="vertical"/>
          <el-tag type="info" size="small">
            总金额: ¥{{ totalAmount.toFixed(2) }}
          </el-tag>
        </div>
      </template>

      <el-table 
        :data="inventoryList" 
        border 
        v-loading="loading"
        height="500"
        style="width: 100%"
        @selection-change="handleSelectionChange">
        
        <el-table-column type="selection" width="55" fixed="left"/>
        <el-table-column type="index" label="序号" width="60" fixed="left"/>
        
        <el-table-column prop="factoryNo" label="厂内编号" width="100" fixed="left"/>
        <el-table-column prop="customerCode" label="客户代码" width="100" fixed="left"/>
        <el-table-column prop="customerName" label="客户名称" width="120" fixed="left"/>
        <el-table-column prop="productName" label="产品名称" width="150" fixed="left" show-overflow-tooltip/>
        
        <el-table-column label="操作" width="120" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="viewDetail(row)">
              详情
            </el-button>
            <el-button type="warning" size="small" @click="openAdjustDialog(row)">
              调整
            </el-button>
          </template>
        </el-table-column>
        
        <el-table-column prop="materialCode" label="物料编码" width="120" show-overflow-tooltip/>
        <el-table-column prop="layers" label="层数" width="80"/>
        <el-table-column prop="thickness" label="板厚" width="80"/>
        <el-table-column prop="surfaceTreatment" label="表面处理" width="100"/>
        <el-table-column prop="solderMask" label="阻焊" width="80"/>
        <el-table-column prop="character" label="字符" width="80"/>
        <el-table-column prop="boardMaterial" label="板材" width="100"/>
        <el-table-column prop="deliverySize" label="交货尺寸" width="120"/>
        <el-table-column prop="totalInboundQuantity" label="总入库数量" width="110"/>
        <el-table-column prop="totalOutboundQuantity" label="总出库数量" width="110"/>
        <el-table-column prop="currentStockQuantity" label="当前库存" width="100">
          <template #default="{ row }">
            <span :style="getStockStyle(row)">{{ row.currentStockQuantity }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="spareQuantity" label="备品数量" width="100"/>
        <el-table-column prop="unitPrice" label="单价" width="100">
          <template #default="{ row }">
            <span v-if="row.unitPrice">{{ row.unitPrice.toFixed(4) }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="totalAmount" label="库存总金额" width="120">
          <template #default="{ row }">
            <span v-if="row.totalAmount" style="color: #E6A23C; font-weight: bold;">
              ¥{{ row.totalAmount.toFixed(2) }}
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="lastInboundDate" label="最后入库日期" width="130"/>
        <el-table-column prop="lastOutboundDate" label="最后出库日期" width="130"/>
        <el-table-column prop="status" label="库存状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)" size="small">
              {{ row.status }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="minStockQuantity" label="预警值" width="80"/>
        <el-table-column prop="salesperson" label="业务员" width="100"/>
      </el-table>

      <!-- 分页组件 -->
      <div class="pagination-wrapper">
        <div class="pagination-info">
          <el-button 
            v-if="selectedItems.length > 0" 
            type="warning" 
            size="small"
            @click="batchAdjustStock">
            批量调整库存 ({{ selectedItems.length }})
          </el-button>
        </div>
        <el-pagination
          :current-page="pagination.current"
          :page-size="pagination.size"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange">
        </el-pagination>
      </div>
    </el-card>

    <!-- 库存详情弹窗 -->
    <el-dialog 
      v-model="detailDialogVisible" 
      title="库存详情" 
      width="800px">
      
      <el-descriptions :column="2" border v-if="currentItem">
        <el-descriptions-item label="厂内编号">{{ currentItem.factoryNo }}</el-descriptions-item>
        <el-descriptions-item label="库存状态">
          <el-tag :type="getStatusType(currentItem.status)" size="small">
            {{ currentItem.status }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="客户代码">{{ currentItem.customerCode }}</el-descriptions-item>
        <el-descriptions-item label="客户名称">{{ currentItem.customerName }}</el-descriptions-item>
        <el-descriptions-item label="产品名称">{{ currentItem.productName }}</el-descriptions-item>
        <el-descriptions-item label="物料编码">{{ currentItem.materialCode || '-' }}</el-descriptions-item>
        <el-descriptions-item label="业务员">{{ currentItem.salesperson || '-' }}</el-descriptions-item>
        <el-descriptions-item label="预警值">{{ currentItem.minStockQuantity || 0 }} PCS</el-descriptions-item>
        
        <el-descriptions-item label="PCB技术参数" :span="2">
          <el-row :gutter="20">
            <el-col :span="6">层数: {{ currentItem.layers || '-' }}</el-col>
            <el-col :span="6">板厚: {{ currentItem.thickness || '-' }}</el-col>
            <el-col :span="6">表面处理: {{ currentItem.surfaceTreatment || '-' }}</el-col>
            <el-col :span="6">阻焊: {{ currentItem.solderMask || '-' }}</el-col>
          </el-row>
          <el-row :gutter="20" style="margin-top: 10px;">
            <el-col :span="6">字符: {{ currentItem.character || '-' }}</el-col>
            <el-col :span="6">板材: {{ currentItem.boardMaterial || '-' }}</el-col>
            <el-col :span="6">交货尺寸: {{ currentItem.deliverySize || '-' }}</el-col>
            <el-col :span="6"></el-col>
          </el-row>
        </el-descriptions-item>
        
        <el-descriptions-item label="总入库数量">
          <span style="color: #67C23A; font-weight: bold;">{{ currentItem.totalInboundQuantity }} PCS</span>
        </el-descriptions-item>
        <el-descriptions-item label="总出库数量">
          <span style="color: #E6A23C; font-weight: bold;">{{ currentItem.totalOutboundQuantity }} PCS</span>
        </el-descriptions-item>
        <el-descriptions-item label="当前库存数量">
          <span :style="getStockStyle(currentItem)" style="font-weight: bold; font-size: 16px;">
            {{ currentItem.currentStockQuantity }} PCS
          </span>
        </el-descriptions-item>
        <el-descriptions-item label="备品数量">{{ currentItem.spareQuantity || 0 }} PCS</el-descriptions-item>
        <el-descriptions-item label="单价">
          <span v-if="currentItem.unitPrice">¥{{ currentItem.unitPrice.toFixed(4) }}</span>
          <span v-else>-</span>
        </el-descriptions-item>
        <el-descriptions-item label="库存总金额">
          <span v-if="currentItem.totalAmount" style="color: #E6A23C; font-weight: bold; font-size: 16px;">
            ¥{{ currentItem.totalAmount.toFixed(2) }}
          </span>
          <span v-else>-</span>
        </el-descriptions-item>
        <el-descriptions-item label="最后入库日期">{{ currentItem.lastInboundDate || '-' }}</el-descriptions-item>
        <el-descriptions-item label="最后出库日期">{{ currentItem.lastOutboundDate || '-' }}</el-descriptions-item>
      </el-descriptions>

      <template #footer>
        <el-button @click="detailDialogVisible = false">关闭</el-button>
        <el-button type="warning" @click="openAdjustDialogFromDetail">库存调整</el-button>
      </template>
    </el-dialog>

    <!-- 库存调整弹窗 -->
    <el-dialog 
      v-model="adjustDialogVisible" 
      title="库存调整" 
      width="600px"
      :close-on-click-modal="false">
      
      <el-form :model="adjustForm" :rules="adjustRules" ref="adjustFormRef" label-width="120px">
        <el-form-item label="厂内编号">
          <el-input v-model="adjustForm.factoryNo" readonly/>
        </el-form-item>
        
        <el-form-item label="产品名称">
          <el-input v-model="adjustForm.productName" readonly/>
        </el-form-item>
        
        <el-form-item label="当前库存">
          <el-input v-model="adjustForm.currentStock" readonly>
            <template #append>PCS</template>
          </el-input>
        </el-form-item>
        
        <el-form-item label="调整类型" prop="adjustmentType">
          <el-radio-group v-model="adjustForm.adjustmentType">
            <el-radio label="盘盈">盘盈（增加）</el-radio>
            <el-radio label="盘亏">盘亏（减少）</el-radio>
          </el-radio-group>
        </el-form-item>
        
        <el-form-item label="调整数量" prop="adjustmentQuantity">
          <el-input-number 
            v-model="adjustForm.adjustmentQuantity" 
            :min="1" 
            controls-position="right"
            style="width: 100%;"
            placeholder="请输入调整数量">
          </el-input-number>
        </el-form-item>
        
        <el-form-item label="调整后库存">
          <el-input :value="getAdjustedStock()" readonly>
            <template #append>PCS</template>
          </el-input>
        </el-form-item>
        
        <el-form-item label="调整日期" prop="adjustmentDate">
          <el-date-picker 
            v-model="adjustForm.adjustmentDate" 
            type="date" 
            placeholder="选择调整日期"
            value-format="YYYY-MM-DD"
            style="width: 100%;">
          </el-date-picker>
        </el-form-item>
        
        <el-form-item label="调整原因" prop="reason">
          <el-input 
            v-model="adjustForm.reason" 
            type="textarea" 
            :rows="3" 
            placeholder="请输入调整原因"
            maxlength="200"
            show-word-limit>
          </el-input>
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="adjustDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleAdjustStock" :loading="adjustLoading">
          确认调整
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  getInventoryList, 
  adjustInventory, 
  getLowStockItems,
  getCustomerOptions, 
  getEmployeeOptions 
} from '@/api/warehouse'
import { Search, Refresh, RefreshLeft, Warning } from '@element-plus/icons-vue'

export default {
  name: 'InventoryManagement',
  components: {
    Search,
    Refresh,
    RefreshLeft,
    Warning
  },
  setup() {
    const loading = ref(false)
    const lowStockLoading = ref(false)
    const adjustLoading = ref(false)
    const detailDialogVisible = ref(false)
    const adjustDialogVisible = ref(false)
    const adjustFormRef = ref()
    const currentItem = ref(null)

    // 搜索表单
    const searchForm = reactive({
      customerCode: '',
      customerName: '',
      productName: '',
      materialCode: '',
      factoryNo: '',
      salesperson: '',
      status: '',
      minStock: null
    })

    // 库存调整表单
    const adjustForm = reactive({
      id: '',
      factoryNo: '',
      productName: '',
      currentStock: 0,
      adjustmentType: '盘盈',
      adjustmentQuantity: 1,
      adjustmentDate: new Date().toISOString().split('T')[0],
      reason: ''
    })

    // 库存调整表单验证规则
    const adjustRules = {
      adjustmentType: [
        { required: true, message: '请选择调整类型', trigger: 'change' }
      ],
      adjustmentQuantity: [
        { required: true, message: '请输入调整数量', trigger: 'blur' },
        { type: 'number', min: 1, message: '调整数量必须大于0', trigger: 'blur' }
      ],
      adjustmentDate: [
        { required: true, message: '请选择调整日期', trigger: 'change' }
      ],
      reason: [
        { required: true, message: '请输入调整原因', trigger: 'blur' }
      ]
    }

    // 分页信息
    const pagination = reactive({
      current: 1,
      size: 20,
      total: 0
    })

    // 库存列表
    const inventoryList = ref([])
    const lowStockItems = ref([])
    const selectedItems = ref([])
    
    // 基础数据
    const customers = ref([])
    const employees = ref([])

    // 计算属性：搜索参数
    const searchParams = computed(() => {
      const params = {
        current: pagination.current,
        size: pagination.size,
        ...searchForm
      }
      
      // 移除空值
      Object.keys(params).forEach(key => {
        if (params[key] === '' || params[key] === null || params[key] === undefined) {
          delete params[key]
        }
      })
      
      return params
    })

    // 计算总金额
    const totalAmount = computed(() => {
      return inventoryList.value.reduce((sum, item) => {
        return sum + (item.totalAmount || 0)
      }, 0)
    })

    // 获取库存列表
    const fetchInventoryList = async () => {
      try {
        loading.value = true
        const response = await getInventoryList(searchParams.value)
        
        if (response.code === 200) {
          inventoryList.value = response.data.records || []
          pagination.total = response.data.total || 0
        }
      } catch (error) {
        console.error('获取库存列表失败:', error)
        ElMessage.error('获取库存列表失败')
      } finally {
        loading.value = false
      }
    }

    // 获取低库存预警
    const fetchLowStockItems = async () => {
      try {
        lowStockLoading.value = true
        const response = await getLowStockItems()
        
        if (response.code === 200) {
          lowStockItems.value = response.data || []
          if (lowStockItems.value.length > 0) {
            ElMessage.warning(`发现 ${lowStockItems.value.length} 项库存不足，请及时补货！`)
          } else {
            ElMessage.success('暂无库存预警')
          }
        }
      } catch (error) {
        console.error('获取库存预警失败:', error)
        ElMessage.error('获取库存预警失败')
      } finally {
        lowStockLoading.value = false
      }
    }

    // 获取基础数据
    const fetchBaseData = async () => {
      try {
        const [customerRes, employeeRes] = await Promise.all([
          getCustomerOptions(),
          getEmployeeOptions()
        ])
        
        if (customerRes.code === 200) {
          customers.value = customerRes.data || []
        }
        
        if (employeeRes.code === 200) {
          employees.value = employeeRes.data || []
        }
      } catch (error) {
        console.error('获取基础数据失败:', error)
      }
    }

    // 搜索
    const handleSearch = () => {
      pagination.current = 1
      fetchInventoryList()
    }

    // 重置搜索
    const resetSearch = () => {
      Object.assign(searchForm, {
        customerCode: '',
        customerName: '',
        productName: '',
        materialCode: '',
        factoryNo: '',
        salesperson: '',
        status: '',
        minStock: null
      })
      pagination.current = 1
      fetchInventoryList()
    }

    // 刷新数据
    const refreshData = () => {
      fetchInventoryList()
      fetchLowStockItems()
    }

    // 分页变化
    const handleSizeChange = (val) => {
      pagination.size = val
      pagination.current = 1
      fetchInventoryList()
    }

    const handleCurrentChange = (val) => {
      pagination.current = val
      fetchInventoryList()
    }

    // 选择变化
    const handleSelectionChange = (selection) => {
      selectedItems.value = selection
    }

    // 查看详情
    const viewDetail = (row) => {
      currentItem.value = row
      detailDialogVisible.value = true
    }

    // 打开调整弹窗
    const openAdjustDialog = (row) => {
      Object.assign(adjustForm, {
        id: row.id,
        factoryNo: row.factoryNo,
        productName: row.productName,
        currentStock: row.currentStockQuantity,
        adjustmentType: '盘盈',
        adjustmentQuantity: 1,
        adjustmentDate: new Date().toISOString().split('T')[0],
        reason: ''
      })
      adjustDialogVisible.value = true
    }

    // 从详情页打开调整弹窗
    const openAdjustDialogFromDetail = () => {
      detailDialogVisible.value = false
      openAdjustDialog(currentItem.value)
    }

    // 计算调整后库存
    const getAdjustedStock = () => {
      if (!adjustForm.adjustmentQuantity) return adjustForm.currentStock
      
      if (adjustForm.adjustmentType === '盘盈') {
        return adjustForm.currentStock + adjustForm.adjustmentQuantity
      } else {
        return Math.max(0, adjustForm.currentStock - adjustForm.adjustmentQuantity)
      }
    }

    // 执行库存调整
    const handleAdjustStock = async () => {
      try {
        await adjustFormRef.value.validate()
        
        // 验证盘亏数量
        if (adjustForm.adjustmentType === '盘亏' && adjustForm.adjustmentQuantity > adjustForm.currentStock) {
          ElMessage.error('盘亏数量不能超过当前库存')
          return
        }
        
        await ElMessageBox.confirm(
          `确认执行库存调整操作吗？\n调整类型: ${adjustForm.adjustmentType}\n调整数量: ${adjustForm.adjustmentQuantity} PCS\n调整后库存: ${getAdjustedStock()} PCS`,
          '确认调整',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }
        )

        adjustLoading.value = true
        const response = await adjustInventory(adjustForm.id, adjustForm)
        
        if (response.code === 200) {
          ElMessage.success('库存调整成功')
          adjustDialogVisible.value = false
          fetchInventoryList() // 刷新列表
        }
      } catch (error) {
        if (error !== 'cancel') {
          console.error('库存调整失败:', error)
          ElMessage.error('库存调整失败')
        }
      } finally {
        adjustLoading.value = false
      }
    }

    // 批量调整库存
    const batchAdjustStock = () => {
      ElMessage.info('批量调整功能开发中...')
    }

    // 获取库存数量样式
    const getStockStyle = (row) => {
      if (row.currentStockQuantity <= 0) {
        return { color: '#F56C6C', fontWeight: 'bold' }
      } else if (row.currentStockQuantity <= (row.minStockQuantity || 0)) {
        return { color: '#E6A23C', fontWeight: 'bold' }
      } else {
        return { color: '#67C23A', fontWeight: 'bold' }
      }
    }

    // 获取状态类型
    const getStatusType = (status) => {
      switch (status) {
        case '有库存':
          return 'success'
        case '预警':
          return 'warning'
        case '无库存':
          return 'danger'
        default:
          return 'info'
      }
    }

    // 初始化
    onMounted(() => {
      fetchBaseData()
      fetchInventoryList()
      fetchLowStockItems()
    })

    return {
      loading,
      lowStockLoading,
      adjustLoading,
      detailDialogVisible,
      adjustDialogVisible,
      adjustFormRef,
      currentItem,
      searchForm,
      adjustForm,
      adjustRules,
      pagination,
      inventoryList,
      lowStockItems,
      selectedItems,
      customers,
      employees,
      totalAmount,
      handleSearch,
      resetSearch,
      refreshData,
      handleSizeChange,
      handleCurrentChange,
      handleSelectionChange,
      viewDetail,
      openAdjustDialog,
      openAdjustDialogFromDetail,
      getAdjustedStock,
      handleAdjustStock,
      batchAdjustStock,
      fetchLowStockItems,
      getStockStyle,
      getStatusType
    }
  }
}
</script>

<style scoped>
.inventory-management {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0;
  color: #303133;
}

.low-stock-alert {
  margin-bottom: 20px;
}

.low-stock-details {
  margin-top: 8px;
  font-size: 14px;
}

.search-card {
  margin-bottom: 20px;
}

.search-form {
  margin-bottom: 0;
}

.table-card {
  margin-bottom: 20px;
}

.pagination-wrapper {
  margin-top: 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.pagination-info {
  flex: 1;
}

.el-form-item {
  margin-bottom: 18px;
}

.el-table {
  font-size: 14px;
}

.el-table .el-table__cell {
  padding: 8px 0;
}

:deep(.el-input-number .el-input__inner) {
  text-align: left;
}

:deep(.el-descriptions-item__label) {
  font-weight: bold;
  background-color: #fafafa;
}
</style> 